<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Loader;
use think\Page;
use think\Validate;
use \app\admin\model\Article as Articles;
use \app\admin\model\ArticleCategory;
use \app\admin\model\Fotu;
use \app\admin\model\FotuCategory;
use \app\admin\model\Investigate;
use \app\admin\model\InvestigateCategory;

class Article extends Api
{
    protected $noNeedLogin = ['getArticleCategoryList',
        'getArticleList', 'getArticleInfo', 'getInvestigateCategoryList',
        'getInvestigateList', 'getInvestigateInfo', 'getFotuCategoryList', 'getCateList',
        'getFotuList', 'getFotuInfo'];
    protected $noNeedRight = '*';
    protected $user_id     = 0;

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
    }

    /**
     * @MethodName 大灣區資訊分類
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getArticleCategoryList($value = '')
    {
        $model = new ArticleCategory;
        $list  = $model
            ->field('id,image,name,createtime')
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功', $list);
    }

    /**
     * @MethodName 獲取大灣區資訊列表
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getArticleList($value = '')
    {
        $cat_id   = $this->request->post("cat_id", 0);
        $ky       = $this->request->post("ky", '');
        $where    = [];
        $where_or = [];
        if ($cat_id) {
            $where['cat_id'] = $cat_id;
        }
        if ($ky) {
            $arr = cnChangeStr($ky);
            if ($arr['cn_f'] == $arr['cn']) {
                $where_1['title'] = ['like', "%$ky%"];
            } else {
                $where_1['title']  = ['like', "%" . $arr['cn_f'] . "%"];
                $where_or['title'] = ['like', "%" . $arr['cn'] . "%"];

            }
            $subQuery = Db::name('article')
                ->field('id,images,title,content,createtime,cat_id,deletetime,weigh')
                ->where($where_1)
                ->whereOr($where_or)
                ->buildSql();
            $model = Db::table($subQuery . ' a');
            $total = $model
                ->where($where)
                ->count();
            $page = new Page($total, 10);
            $list = Db::table($subQuery . ' b')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('weigh desc,id desc')
                ->select();

        } else {
            $model               = Db::name('article');
            $where['deletetime'] = null;
            $total               = $model
                ->where($where)
                ->count();

            $page = new Page($total, 10);

            $list = $model
                ->field('id,images,title,content,createtime')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('weigh desc,id desc')
                ->select();
        }

        foreach ($list as $key => &$value) {
            $value['collection_num'] = db('collection')->where(['type' => '1', 'relation_id' => $value['id']])->count();
        }

        unset($value);

        if ($this->user_id) {
            // 存儲用戶瀏覽記錄
            setArticleHistory($this->user_id, 1, 0);
        }

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取大灣區資訊詳情
     * @Author     Allen
     * @DateTime   2021-10-04T15:42:20+0800
     * @return     [type]
     */
    public function getArticleInfo()
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $model = new Articles;
        $info  = $model
            ->field('id,images,title,introduction,content,createtime,qid')
            ->where(['id' => $rq_data['id']])
            ->find();

        $model->where(['id' => $rq_data['id']])->setInc('click');
        if ($info) {
            $info['collection_num'] = db('collection')
                ->where(['type' => '1', 'relation_id' => $info['id']])
                ->count();

            $info['collection_status'] = db('collection')
                ->where(['type' => '1', 'relation_id' => $info['id'], 'user_id' => $this->user_id])
                ->count();

            if ($this->user_id) {
                // 存儲用戶瀏覽記錄
                setArticleHistory($this->user_id, 1, $info['id']);
            }
        }

        $this->success('請求成功', $info ? $info : []);
    }

    /**
     * @MethodName 大灣區資訊操作收藏
     * @Author     Allen
     * @DateTime   2021-10-04T16:13:20+0800
     * @param      string
     */
    public function setArticleCollection($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Articles;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }
        $collection_status = db('collection')
            ->where(['type' => '1', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
            ->count();

        if ($collection_status) {
            $status = db('collection')
                ->where(['type' => '1', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
                ->delete();

        } else {
            $insert_arr                = [];
            $insert_arr['user_id']     = $this->user_id;
            $insert_arr['type']        = '1';
            $insert_arr['relation_id'] = $rq_data['id'];
            $insert_arr['createtime']  = time();
            $status                    = db('collection')->insert($insert_arr);
        }
        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    /**
     * @MethodName 大灣區調查分類
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getInvestigateCategoryList($value = '')
    {
        $model = new InvestigateCategory;
        $list  = $model
            ->field('id,image,name,createtime')
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功', $list);
    }

    /**
     * @MethodName 獲取大灣區調查列表
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getInvestigateList($value = '')
    {
        $cat_id   = $this->request->post("cat_id", 0);
        $ky       = $this->request->post("ky", '');
        $where    = [];
        $where_or = [];
        if ($cat_id) {
            $where['cat_id'] = $cat_id;
        }
        if ($ky) {
            $arr = cnChangeStr($ky);
            if ($arr['cn_f'] == $arr['cn']) {
                $where_1['title'] = ['like', "%$ky%"];
            } else {
                $where_1['title']  = ['like', "%" . $arr['cn_f'] . "%"];
                $where_or['title'] = ['like', "%" . $arr['cn'] . "%"];

            }
            $subQuery = Db::name('investigate')
                ->field('id,images,title,content,createtime,cat_id,deletetime,weigh')
                ->where($where_1)
                ->whereOr($where_or)
                ->buildSql();
            $model = Db::table($subQuery . ' a');
            $total = $model
                ->where($where)
                ->count();
            $page = new Page($total, 10);
            $list = Db::table($subQuery . ' b')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('weigh desc,id desc')
                ->select();

        } else {
            $model               = Db::name('investigate');
            $where['deletetime'] = null;
            $total               = $model
                ->where($where)
                ->count();

            $page = new Page($total, 10);
            $list = $model
                ->field('id,images,title,content,createtime,cat_id')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)->order('weigh desc,id desc')
                ->select();
        }

        foreach ($list as $key => &$value) {
            $value['collection_num'] = db('collection')
                ->where(['type' => '2', 'relation_id' => $value['id']])
                ->count();
            $value['cat_name'] =Db::name('investigate_category')->where('id',$value['cat_id'])->value('name');
        }

        unset($value);

        if ($this->user_id) {
            // 存儲用戶瀏覽記錄
            setArticleHistory($this->user_id, 2, 0);
        }

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取大灣區調查詳情
     * @Author     Allen
     * @DateTime   2021-10-04T15:42:20+0800
     * @return     [type]
     */
    public function getInvestigateInfo()
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $model = new Investigate;
        $info  = $model
            ->field('id,images,title,introduction,content,createtime,qid')
            ->where(['id' => $rq_data['id']])
            ->find();

        $model
            ->where(['id' => $rq_data['id']])
            ->setInc('click');

        if ($info) {
            $info['collection_num'] = db('collection')
                ->where(['type' => '2', 'relation_id' => $info['id']])
                ->count();

            $info['collection_status'] = db('collection')
                ->where(['type' => '2', 'relation_id' => $info['id'], 'user_id' => $this->user_id])
                ->count();

            if ($this->user_id) {
                // 存儲用戶瀏覽記錄
                setArticleHistory($this->user_id, 2, $info['id']);
            }

        }

        $this->success('請求成功', $info ? $info : []);
    }

    /**
     * @MethodName 大灣區調查操作收藏
     * @Author     Allen
     * @DateTime   2021-10-04T16:12:36+0800
     * @param      string
     */
    public function setInvestigateCollection($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Investigate;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }
        $collection_status = db('collection')
            ->where(['type' => '2', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
            ->count();

        if ($collection_status) {
            $status = db('collection')
                ->where(['type' => '2', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
                ->delete();
        } else {
            $insert_arr                = [];
            $insert_arr['user_id']     = $this->user_id;
            $insert_arr['type']        = '2';
            $insert_arr['relation_id'] = $rq_data['id'];
            $insert_arr['createtime']  = time();
            $status                    = db('collection')->insert($insert_arr);
        }
        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    /**
     * @MethodName 工聯中心分類
     * @Author     Allen
     * @DateTime   2021-10-04T14:59:51+0800
     * @param      string
     * @return     [type]
     */
    public function getFotuCategoryList($value = '')
    {
        $model = new FotuCategory;
        $list  = $model
            ->field('id,image,name,createtime')
            ->order('weigh desc,id desc')
            ->select();

        $this->success('請求成功', $list);
    }

    /**
     * @MethodName 獲取工聯中心列表
     * @Author     Allen
     * @DateTime   2021-10-04T14:55:12+0800
     * @param      string
     * @return     [array]
     */
    public function getFotuList($value = '')
    {
        $cat_id = $this->request->post("cat_id", 0);
        $ky     = $this->request->post("ky", '');
        // $model = new Fotu;

        $where    = [];
        $where_or = [];
        if ($cat_id) {
            $where['cat_id'] = $cat_id;
        }
        if ($ky) {
            $arr = cnChangeStr($ky);
            if ($arr['cn_f'] == $arr['cn']) {
                $where_1['title'] = ['like', "%$ky%"];
            } else {
                $where_1['title']  = ['like', "%" . $arr['cn_f'] . "%"];
                $where_or['title'] = ['like', "%" . $arr['cn'] . "%"];

            }
            $subQuery = Db::name('fotu')
                ->field('id,images,title,content,createtime,cat_id,deletetime,weigh')
                ->where($where_1)
                ->whereOr($where_or)
                ->buildSql();
            $model = Db::table($subQuery . ' a');
            $total = $model
                ->where($where)
                ->count();
            $page = new Page($total, 10);
            $list = Db::table($subQuery . ' b')
                ->where($where)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('weigh desc,id desc')
                ->select();

        } else {
            $model               = Db::name('fotu');
            $where['deletetime'] = null;
            $total               = $model
                ->where($where)
                ->whereOr($where_or)
                ->count();

            $page = new Page($total, 10);
            $list = $model
            // ->field('id,images,title,content,createtime')
            ->field('id,title,images,createtime')
                ->where($where)
                ->whereOr($where_or)
                ->limit($page->firstRow . ',' . $page->listRows)
                ->order('weigh desc,id desc')
                ->select();
        }

        foreach ($list as $key => &$value) {
            $value['collection_num'] = db('collection')
                ->where(['type' => '3', 'relation_id' => $value['id']])
                ->count();
        }

        unset($value);

        if ($this->user_id) {
            // 存儲用戶瀏覽記錄
            setArticleHistory($this->user_id, 3, 0);
        }

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取工聯中心詳情
     * @Author     Allen
     * @DateTime   2021-10-04T15:42:20+0800
     * @return     [type]
     */
    public function getFotuInfo()
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $model = new Fotu;
        $info  = $model
            ->field('id,images,title,introduction,content,address_name,address,lng,lat,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        $model->where(['id' => $rq_data['id']])->setInc('click');

        if ($info) {
            $info['collection_num'] = db('collection')
                ->where(['type' => '3', 'relation_id' => $info['id']])
                ->count();

            $info['collection_status'] = db('collection')
                ->where(['type' => '3', 'relation_id' => $info['id'], 'user_id' => $this->user_id])
                ->count();

            if ($this->user_id) {
                // 存儲用戶瀏覽記錄
                setArticleHistory($this->user_id, 3, $info['id']);
            }
        }

        $this->success('請求成功', $info ? $info : []);
    }

    /**
     * @MethodName 工聯中心操作收藏
     * @Author     Allen
     * @DateTime   2021-10-04T16:12:36+0800
     * @param      string
     */
    public function setFotuCollection($value = '')
    {
        $rq_data  = $this->request->param();
        $validate = Loader::validate('Article');
        if (! $validate->scene('info')->check($rq_data)) {
            $this->error($validate->getError());
        }
        $model = new Fotu;
        $info  = $model
            ->field('id,images,title,content,createtime')
            ->where(['id' => $rq_data['id']])
            ->find();

        if (! $info) {
            $this->error('操作失敗');
        }
        $collection_status = db('collection')
            ->where(['type' => '3', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
            ->count();

        if ($collection_status) {
            $status = db('collection')
                ->where(['type' => '3', 'relation_id' => $rq_data['id'], 'user_id' => $this->user_id])
                ->delete();
        } else {
            $insert_arr                = [];
            $insert_arr['user_id']     = $this->user_id;
            $insert_arr['type']        = '3';
            $insert_arr['relation_id'] = $rq_data['id'];
            $insert_arr['createtime']  = time();
            $status                    = db('collection')->insert($insert_arr);
        }
        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    public function getCateList()
    {
        $arr                = [];
        $arr['activity']    = Db::name('affiliated_center')->where(['deletetime' => null])->field('id,name')->select();
        $arr['fotu']        = Db::name('fotu_category')->where(['deletetime' => null])->field('id,name')->select();
        $arr['article']     = Db::name('article_category')->where(['deletetime' => null])->field('id,name')->select();
        $arr['investigate'] = Db::name('investigate_category')->where(['deletetime' => null])->field('id,name')->select();
        $arr['activity']    = Db::name('activity_category')->where(['deletetime' => null])->field('id,name')->select();
        $this->success('操作成功', $arr);

    }
}
